import { bufferUtils } from "../utils/bufferUtils"

/*
*前面6字节指定消息类型，string或者file
 */
const __MESSAGE_TYPE_BUFFER_SIZE__ = 10
/*
*消息类型后面20字节指定消息key
 */
const __MESSAGE_KEY_BUFFER_SIZE__ = 20
/*
*key后面20字节指定文件名称
 */
const __MESSAGE_FILE_NAME_BUFFER_SIZE__ = 20
/*
*文件名称后面6字节指定文件后缀
 */
const __MESSAGE_FILE_EXT_BUFFER_SIZE__ = 20

export class FileMessageDistributor {
  private listeners: Array<(message: string) => void>

  subscribe(handle: (message: string) => void) {
    this.listeners.push(handle)
    return () => {
      this.listeners.splice(this.listeners.findIndex(l => l === handle), 1)
    }
  }

  notify(message: string) {
    this.listeners.forEach(l => l(message))
  }

  distribute(value: ArrayBuffer) {
    let buffer = value.slice(__MESSAGE_TYPE_BUFFER_SIZE__)
    let message = bufferUtils.bufferToStr(buffer)
    this.notify(message)
  }

}

export const fileMessageDistributor = new FileMessageDistributor()